package yxy.game.pm2.active.command.bottlewish;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.actwishchargereward;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.ActiveModule_心愿瓶;
import yxy.game.pm2.active.module.actfavoritewarlord.FavouritePackage;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.currency.Currencies;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.BottleWishMessage;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.module.CurrencyHandle;

import java.util.*;

/****************************************
 * @name CMD_Active_心愿瓶_BottleWishChargeReceive
 * @description 心愿瓶累充领取
 * @author 梁健彬
 * @since 2022-08-22
 ***************************************/
@MessageType(proto = Command.BottleWishChargeReceive, classtype = BottleWishMessage.BottleWishChargeReceiveRequest.class)
public class CMD_Active_心愿瓶_BottleWishChargeReceive extends Command<BottleWishMessage.BottleWishChargeReceiveRequest> {

    @Override
    public void execute(MessageSource messageSource, BottleWishMessage.BottleWishChargeReceiveRequest request) throws Exception {
        String playercode = messageSource.getTag();
        int id = request.getId();
        BottleWishMessage.BottleWishChargeReceiveResponse.Builder response = BottleWishMessage.BottleWishChargeReceiveResponse.newBuilder();
        ActiveModule_心愿瓶 am = ActiveModule_心愿瓶.get(playercode, false);
        try {

            if (am == null) {
                send(messageSource, response, Result.ActNoOpen);
                return;
            }

            if (!am.running()) {
                send(messageSource, response, Result.ActNoOpen);
                return;
            }

            FavouritePackage favouritePackage = null;
            ArrayList<FavouritePackage> accumulateDgifts = am.getAccumulateDgifts();
            for (FavouritePackage fp : accumulateDgifts) {
                if (fp.getId() != id) continue;
                if (fp.isCanBuy()) {
                    send(messageSource, response, Result.BottleWishRegisterCantRepeatedReward);//不能重复领取
                    return;
                }

                if (am.getTotalChargeMoney() < fp.getCondition()) {
                    send(messageSource, response, Result.BottleWishAccumulateCantReward);//没达到，不能领取
                    return;
                }

                favouritePackage = fp;
            }

            if (favouritePackage == null) {
                send(messageSource, response, Result.DataError);
                return;
            }

            //todo 领取奖励
            CurrencyHandle currencyHandle = new CurrencyHandle();
            if (am.tryLock()) {
                int dataId = favouritePackage.getId();
                actwishchargereward data = DataCenter.getData(dataId, actwishchargereward.class);
                Currencies curs = new Currencies(Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum())); //奖励
                Collection<PackageMessage.Item> items = new CurrencyHandle().packItems(curs);
                currencyHandle.addCurrency(playercode, CCReason.心愿瓶, curs);
                response.addAllItem(items);
                am.getHasRewardId().add(dataId);
                am.set();
            }

            //todo 累充信息
            ArrayList<BottleWishMessage.BottleWishCharge> list = getData(am);
            response.addAllList(list);
            send(messageSource, response, Result.Success);
        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);
        } finally {
            am.unlock();
        }
    }


    private void send(MessageSource messageSource, BottleWishMessage.BottleWishChargeReceiveResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }

    /**
     * 累充信息
     *
     * @param am
     * @return
     */
    public ArrayList<BottleWishMessage.BottleWishCharge> getData(ActiveModule_心愿瓶 am) {
        int chargeMoney = am.getTotalChargeMoney();
        ArrayList<Integer> hasRewardId = am.getHasRewardId();

        ArrayList<BottleWishMessage.BottleWishCharge> list = new ArrayList<>();

        Map<String, actwishchargereward> allData = DataCenter.getAllData(actwishchargereward.class);

        ArrayList<FavouritePackage> accumulateDgifts = am.getAccumulateDgifts();

        for (FavouritePackage fp : accumulateDgifts) {

            BottleWishMessage.BottleWishCharge.Builder build = BottleWishMessage.BottleWishCharge.newBuilder();

            actwishchargereward data = allData.get(String.valueOf(fp.getId()));
            build.setId(data.getId());//表id
            Currencies curs = new Currencies(Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum())); //奖励
            Collection<PackageMessage.Item> items = new CurrencyHandle().packItems(curs);
            build.addAllRewards(items);//商品物品
            build.setMaxValue(data.getCondition());
            int nowValue = chargeMoney >= data.getCondition() ? data.getCondition() : chargeMoney;
            build.setNowValue(nowValue);
            build.setDesc(data.getDesc());
            Boolean isGot = !hasRewardId.contains(fp.getId()) ? false : true;
            build.setIsGot(isGot);
            list.add(build.build());
        }

        //从低到高排序
        Collections.sort(list, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                BottleWishMessage.BottleWishCharge builder1 = (BottleWishMessage.BottleWishCharge) o1;
                BottleWishMessage.BottleWishCharge builder2 = (BottleWishMessage.BottleWishCharge) o2;
                return builder1.getMaxValue() - builder2.getMaxValue();
            }
        });

        return list;
    }
}
